package sendtemplateinterfacelogic

import (
	"context"
	"errors"

	"dfx_cmdb/cmdb-sendmsg-rpc/internal/svc"
	cmdb_database_sync "dfx_cmdb/cmdb-sendmsg-rpc/types/cmdb-database-sync"
	cmdbsendmsg "dfx_cmdb/models/cmdb-sendmsg"

	"github.com/zeromicro/go-zero/core/logx"
)

type InsertSendTemplateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewInsertSendTemplateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InsertSendTemplateLogic {
	return &InsertSendTemplateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// InsertSendTemplate 新增一个发送模板
func (l *InsertSendTemplateLogic) InsertSendTemplate(in *cmdb_database_sync.SendTemplateRequest) (*cmdb_database_sync.PublicMsgResponse, error) {
	tx := l.svcCtx.DB
	

	err := tx.Model(&cmdbsendmsg.SendTemplate{}).Where("template_name = ?", in.TemplateName).First(&cmdbsendmsg.SendTemplate{}).Error
	if err == nil {
		return &cmdb_database_sync.PublicMsgResponse{
			Msg: "发送模板已存在",
		}, errors.New("发送模板已存在")
	}

	sendTemplate := cmdbsendmsg.SendTemplate{
		TemplateName: in.TemplateName,
		TemplateMsg:  in.TemplateMsg,
	}

	err = tx.Create(&sendTemplate).Error
	if err != nil {
		return &cmdb_database_sync.PublicMsgResponse{
			Msg: err.Error(),
		}, nil
	}
	logx.Infof("插入数据成功，插入数据: %v", sendTemplate)
	return &cmdb_database_sync.PublicMsgResponse{
		Msg: "插入数据成功",
	}, nil
}
